﻿using FoursquareTask.DAL;
using FoursquareTask.Helpers;
using FoursquareTask.Models;
using FoursquareTask.TOs;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace FoursquareTask.Managers
{
    public class SearchManager : IDisposable
    {       

        public FoursquareContext Db { get; set; }        

        public VenueConverter Converter { get; set; }

        public RequestHelper ReqHelp { get; set; }

        public SearchManager()
        {
            Converter = new VenueConverter();
            Db = new FoursquareContext();
            ReqHelp = new RequestHelper();
        }

        public List<Search> GetAllSearches()
        {
            return Db.Searches.ToList();
        }

        public Search GetSearchByText(string id)
        {
            return Db.Searches.Find(id);
        }

        public Search NewSearch(Search search)
        {
            Search lookup = GetSearchByText(search.Text);
            if (lookup == null)
            {
                search.Count = 1;
                Db.Searches.Add(search);
                Db.SaveChanges();                
            }
            else 
            {
                EditSearchCount(lookup);                
            }
            return lookup;
        }

        private Search EditSearchCount(Search search)
        {
            search.Count += 1;
            Db.Entry(search).State = EntityState.Modified;
            Db.SaveChanges();
            return search;
        }
      
        public List<VenueTO>GetTOs4Search(Search search)
        {
            return ReqHelp.GetVenuesDetails(ReqHelp.FindVenues(search.Text));
        }



        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                Db.Dispose();
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }    
        
    }
}